package com.chilly.jdkNio.action.hello;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Created by Chilly Cui on 2021/1/10.
 */
public class NIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 6666);

        //连接服务器
        if (!socketChannel.connect(address)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("因为连接需要时间，客户端不会阻塞，可以做其它工作");
            }
        }

        String sendMsg = "I'm a client";
        ByteBuffer buffer = ByteBuffer.wrap(sendMsg.getBytes());

        //将buffer数据写入到channel
        socketChannel.write(buffer);

        System.in.read();
    }
}
